#include "tcp.h"
#include "config.h"
#include "CPrint.h"

using namespace wakefieldq;

void readcmd(char* fmt, ...);
void printmsg(char* fmt, ...);

char*
	my_sock_ntop(const struct sockaddr* sa, socklen_t salen, char* buf)
{
	char	portstr[8];
	CPrint::msg("AF_INET:%d,sa_family:%d",AF_INET,sa->sa_family);
	switch(sa->sa_family)
	{
	case AF_INET:
		struct sockaddr_in *sin = (struct sockaddr_in*)sa;
		if(inet_ntop(AF_INET, &sin->sin_addr, buf, 128) == NULL)
			return NULL;
		if(ntohs(sin->sin_port) != 0)
			snprintf(portstr, sizeof(portstr), ":%d", ntohs(sin->sin_port));
		strcat(buf, portstr);
	}
	return buf;

}

int main(int argc, char const *argv[])
{

	int		port = 12131;
	pid_t	clipid;
	if(argc == 2)
	{
		int tport = atoi(argv[1]);
		if(tport < 0)
			printf("illegal port number, the port has been setted as: 12131\n");
		else
			port = tport;
	}
	else if(argc < 2)
	{
		printf("the port has been setted as: 12131\n");
	}
	char buf[256];
	bzero(buf, 256);
	CTcp tcp(port);
	CPrint::msg("Start [server] or [connect]");
	CPrint::read(buf);
	while(memcmp(buf, QUIT, sizeof(QUIT)-1) != 0)
	{
		if(memcmp(buf, WAIT, sizeof(WAIT)-1) == 0)
		{
			CPrint::read(buf);
			continue;
		}
		else if(memcmp(buf, START_SERVER, sizeof(START_SERVER)-1) == 0)
		{
			CPrint::msg("START_SERVER");
			int listenfd = tcp.open_listen();
			for ( ; ; )
			{
				CPrint::msg("Waiting...");
				int connfd = tcp.receive();
				if( (clipid = fork()) == 0)
				{

					close(listenfd);
					struct sockaddr_in cliaddr;
					int size = tcp.get_cliaddr(&cliaddr);
					char ipaddr[128];

					if(my_sock_ntop((SA*)&cliaddr, size, ipaddr) != NULL)
						CPrint::msg("we got connection from [%s]", ipaddr);
					else
						CPrint::msg("we got connection from unknown");
					exit(0);
				}
				tcp.Close(connfd);

			}
		}
		else if (memcmp(START_CONNECT, buf, sizeof(START_CONNECT)-1) == 0)
		{
			CPrint::msg("START_CONNECT");
			char ip[256];
			memset(ip, 0, sizeof(ip));
			sscanf(buf, "%*s%s", ip);
			CPrint::msg("connecting to:%s",ip);
			int connfd = tcp.connectto(buf);

		}
		memcpy(buf, WAIT, sizeof(WAIT));
	}
	return 0;
}

